package com.huanletao.tree;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * </p>
 * package: com.huanletao.spring.data
 * description: 计算所有父项目的统计数据。
 * className: demo90
 * author:  踏雪无痕
 * copyright: Copyright (c) 2023/5/23 11:33
 * since: 1.0.0
 */
public class demo90 {

    private static List<TreeData> data = new ArrayList<>();

    static {
        data.add(new TreeData(1L,0L,0L));
        data.add(new TreeData(2L,1L,0L));
        data.add(new TreeData(3L,1L,0L));
        data.add(new TreeData(4L,2L,0L));
        data.add(new TreeData(5L,2L,30L));
        data.add(new TreeData(6L,4L,30L));
        data.add(new TreeData(8L,4L,40L));
        data.add(new TreeData(9L,3L,40L));
        data.add(new TreeData(10L,3L,40L));
        data.add(new TreeData(11L,3L,40L));
        data.add(new TreeData(12L,3L,40L));
    }

    public static void main(String[] args) {
        Long sum = sum(new TreeData(0L, 0L, 0L));
        System.out.println("sum = " + data);
    }

    /**
     * 1.统计所有叶子节点数据。
     *
     * @return
     */
    private static Long sum(TreeData tree) {
        List<TreeData> childrenlist = getChildrenList(tree.getId());
        if (childrenlist.isEmpty()) {
            return tree.getValue();
        }
        Long totoal = 0L;
        for (TreeData treeData : childrenlist) {
            Long sum = sum(treeData);
            totoal+=sum;
        }
        tree.setValue(totoal);
        return totoal;
    }

    private static List<TreeData> getChildrenList(long parentId) {
        return data.stream().filter(item -> item.getParentId() == parentId).collect(Collectors.toList());
    }
}
